package exception;

import java.util.ArrayList;
import org.apache.commons.lang.StringUtils;
import net.sf.json.JSONArray;

/**
 * Custom exception class for throwing multiple validation errors.
 * 
 * @author huangjm.2012, mohameds.2012, sheryl.tay.2012
 */
public class InputValidationErrors extends Exception {

	/**
	 * Stores multiple error messages.
	 */
	private ArrayList<String> errors;

	public InputValidationErrors(String message) {
		errors = new ArrayList<String>();
		errors.add(message);
	}

	public InputValidationErrors(ArrayList<String> messages) {
		errors = messages;
	}

	/*
	 * Returns a String containing all the error messages separated by comma.
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Throwable#getMessage()
	 */
	@Override
	public String getMessage() {
		return StringUtils.join(errors, ",");
	}

	/**
	 * Returns the error message in a JSON Array format
	 * 
	 * @return a JSONArray object with the error message; e.g. ["invalid user"]
	 */
	public JSONArray toJsonArray() {

		// construct a JSON Array and add all the error messages
		JSONArray jsonArray = new JSONArray();
		jsonArray.addAll(errors);

		return jsonArray;
	}

}
